#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# AWL simulator - Server interface
#
# Copyright 2013 Michael Buesch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from __future__ import division, absolute_import, print_function, unicode_literals
from awlsim.core.compat import *

import sys
import getopt

from awlsim.core import *
from awlsim.coreserver import *


def usage():
	printInfo("awlsim-server version %d.%d" % (VERSION_MAJOR, VERSION_MINOR))
	printInfo("")
	printInfo("%s [OPTIONS]" % sys.argv[0])
	printInfo("")
	printInfo("Options:")
	printInfo(" -l|--listen HOST:PORT   Listen on the specified HOST:PORT")
	printInfo("                         Defaults to %s:%d" %\
		  (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT))
	printInfo(" -B|--background         Fork a background process")

def main():
	global opt_listen
	global opt_background

	opt_listen = (AwlSimServer.DEFAULT_HOST, AwlSimServer.DEFAULT_PORT)
	opt_background = False

	try:
		(opts, args) = getopt.getopt(sys.argv[1:],
			"hl:B",
			[ "help", "listen=", "background", ])
	except getopt.GetoptError as e:
		printError(str(e))
		usage()
		return 1
	for (o, v) in opts:
		if o in ("-h", "--help"):
			usage()
			return 0
		if o in ("-l", "--listen"):
			try:
				idx = v.rfind(":")
				if idx <= 0:
					raise ValueError
				opt_listen = (v[:idx], int(v[idx+1:]))
			except ValueError:
				printError("-l|--listen: Invalid host/port")
				sys.exit(1)
		if o in ("-B", "--background"):
			opt_background = True
	if args:
		usage()
		return 1

	exitCode = 0
	try:
		if opt_background:
			interpreter = sys.executable
			assert(interpreter)
			serverProcess = AwlSimServer.start(listenHost = opt_listen[0],
							   listenPort = opt_listen[1],
							   forkInterpreter = interpreter)
			printInfo("Started awlsim server process (PID: %d)" %\
				  serverProcess.pid)
		else:
			exitCode = AwlSimServer.start(listenHost = opt_listen[0],
						      listenPort = opt_listen[1],
						      forkInterpreter = None)
	except AwlSimError as e:
		printError(e.getReport())
		return 1

	return exitCode

if __name__ == "__main__":
	sys.exit(main())
